var ldap = require('ldapjs');
var obj = [ {
	dn : 'dc=structure-net,dc=de',
	attributes : {
		objectclass : [ 'top', 'organization' ],
		o : [ 'dc=structure-net, dc=de' ]
	},
	children : [ {
		dn : 'ou=example2,dc=structure-net,dc=de',
		attributes : {
			objectclass : [ 'top', 'organizationalunit' ],
			ou : [ 'example2' ]
		},
		children : [ {
			dn : 'ou=example3,ou=example2,dc=structure-net,dc=de',
			attributes : {
				objectclass : [ 'top', 'organizationalunit' ],
				ou : [ 'example3' ]
			},
			children : []
		} ]
	} ]
} ];
var handlers = {};
var searchClient = require('./client.js');
searchClient.client.options = {
		url: 'ldap://192.168.1.116:389',
		username: 'administrator@example.com',
		password: 'p4ssw0rd!',
		filter: '(|(objectclass=user)(objectclass=group))',
		scope : 'sub',
		attributeToWalk: 'member',
		base : 'dc=example,dc=com',
		attributes : [ "objectclass","cn", "dn", "member", "memberOf", "attributes" ]
};
searchClient.client.finishedCallback = (function(entries, rootNodes) {
	obj = {
		dn : searchClient.client.options.base,
		objectclass : [ 'top', 'organization' ],
		o : [ searchClient.client.options.base ]
	};
	obj.objectClass = obj.objectclass;
	obj['children'] = [];
	entries.forEach(function(entry) {
		walkThrough(entry, 'children');
	});

	rootNodes.forEach(function(rootNode) {
		obj['children'].push(rootNode);
		walkThrough(rootNode, 'children');
	});
	var server = ldap.createServer();

	server.listen(1389, function() {
		walkThrough(obj, 'children');
		server.search("dc=example,dc=com", function(req, res, next) {

			var handler = handlers[req.dn.toString().replace(/,\s+/g, ',')
					.toLowerCase()];

			handler(req, res, next);
			res.end();
		});
	});
});

searchClient.client.start();

function walkThrough(obj, childAttributeName) {

	var dn = obj.dn.replace(/,\s+/g, ',').toLowerCase();
	handlers[dn] = (function(req, res, next) {
		obj.objectclass = obj.objectClass;
		var objectToSend = {
			dn : obj.dn,
			objectclass : [ 'top', 'organization' ],
			attributes : obj,
		};
		console.log(objectToSend);
		
		if (req.scope == "base") {
			if (req.filter.matches(objectToSend) || req.filter.matches(obj))
				res.send(objectToSend);
		} else if (req.scope == 'one') {
			if (req.filter.matches(objectToSend) || req.filter.matches(obj))
				res.send(objectToSend);
			obj[childAttributeName].forEach(function(obj2) {

				var dn = obj2.dn.replace(/,\s+/g, ',').toLowerCase();
				var handler = handlers[dn];
				req.scope = "base";

				if (typeof (handler) === "undefined") {
				} else {
					handler(req, res, next);
				}
			});
		} else if (req.scope == 'sub') {
			
			if (req.filter.matches(objectToSend) || req.filter.matches(obj)) {
				res.send(objectToSend);
			}
			obj[childAttributeName].forEach(function(obj2) {

				var dn = obj2.dn.replace(/,\s+/g, ',').toLowerCase();
				var handler = handlers[dn];
				if (typeof (handler) === "undefined") {
				} else {
					handler(req, res, next);
				}
			});
		}
	});
}
